package cn.lg.soar.system.biz.modules.message.controller;

import cn.lg.soar.common.constant.SystemConst;
import cn.lg.soar.common.util.current.CurrentTokenInfo;
import cn.lg.soar.common.util.current.ThreadLocalHolder;
import cn.lg.soar.core.manager.IAccessTokenManager;
import cn.lg.soar.core.util.SoarSubscriber;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.biz.modules.message.service.impl.WebSocketServiceImpl;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * websocket服务
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@ServerEndpoint(value = "/"+ ModuleConst.MODULE_NAME + "/ws")
public class WebSocket {
    protected static final Logger logger = LoggerFactory.getLogger(WebSocket.class);

    private static IAccessTokenManager accessTokenManager;
    private static WebSocketServiceImpl manager;

    static {
        SoarSubscriber.subscribeRunner(a -> {
            accessTokenManager = a.getBean(IAccessTokenManager.class);
            manager = a.getBean(WebSocketServiceImpl.class);
        });
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        Map<String, List<String>> params = session.getRequestParameterMap();
        List<String> list = params.get(SystemConst.TOKEN_NAME);
        if (list == null) {
            session.close();
            logger.info("验证失败，关闭连接：{}", session.getId());
            return;
        }
        String token = list.get(0);
        CurrentTokenInfo currentUser = accessTokenManager.verify(token);
        if (currentUser != null) {
            ThreadLocalHolder.setCurrentUser(currentUser);
            manager.onOpen(currentUser.getId(), currentUser.getTokenId(), session);
        } else {
            session.close();
            logger.info("验证失败，关闭连接：{}", session.getId());
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        manager.onClose(session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        manager.onMessage(message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        manager.onError(session, error);
    }

}
